package com.wimcorp.magic.phase;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import com.wimcorp.magic.abilities.Ability;
import com.wimcorp.magic.behaviour.SummoningSickness;
import com.wimcorp.magic.board.CardType;
import com.wimcorp.magic.cards.PlayingCard;
import com.wimcorp.magic.players.Player;
import com.wimcorp.magic.spell.Castable;

public class BeginningPhase extends Phase {

	private Set<Ability> untapObservers = new HashSet<Ability>();
	private Set<Ability> upkeepObservers = new HashSet<Ability>();

	public BeginningPhase(Player activePlayer) {
		super(activePlayer);
	}

	public void execute() {
		untapCards();
		upkeep();
		if (!Turn.isFirstTurn()) {
			drawCard();
		}
		// if (getStack().size() != 0) {
		activateAbilities();
		// }
	}

	private void untapCards() {
		// trigger untap abilities
		for (Ability untapObserver : untapObservers) {
			getActivePlayer().cast(untapObserver);
		}
		if (getStack().size() != 0) {
			// resolve stack
			getStack().resolve();
		}

		getActivePlayer().clearPayment();
		int count = getActivePlayer().untapCards();
		if (count > 0) {
			messagePlayer("Untapping cards... ");
			messageOpponent("Untapping your opponents cards... ");
		}
	}

	private void upkeep() {
		// trigger upkeep abilities
		for (Ability upkeepObserver : upkeepObservers) {
			getActivePlayer().cast(upkeepObserver);
		}
		if (getStack().size() != 0) {
			// resolve stack
			getStack().resolve();
		}
		Collection<PlayingCard> cards = getActivePlayer().getSummoningPlaines().getCards(CardType.ALL);
		for (PlayingCard card : cards) {
			if (card.hasBehaviour(SummoningSickness.instance())) {
				card.removeBehaviour(SummoningSickness.instance());
			}
		}

	}

	private void drawCard() {
		getActivePlayer().drawCard();
	}

	public void registerUntapObserver(Ability ability) {
		untapObservers.add(ability);
	}

	public void registerUpkeepObserver(Ability ability) {
		upkeepObservers.add(ability);
	}

	public void unRegisterUntapObserver(Ability ability) {
		untapObservers.remove(ability);
	}

	public void unRegisterUpkeepObserver(Ability ability) {
		upkeepObservers.remove(ability);
	}

}
